package com.greenhouse.protocol.internalmessage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSONObject;
import com.greenhouse.protocol.ChannelService;

/**
 *
 * @版权 : Copyright (c) 2020 儒安物联技术研发中心
 * @author: 雷扬
 * @E-mail: leiyang@runaiot.com
 * @版本: 1.0
 * @创建日期: 2021年5月8日 上午9:50:03
 * @ClassName MessageCenter
 * @类描述-Description: TODO(这里用一句话描述这个方法的作用)
 * @修改记录:
 * @版本: 1.0
 */
public class MessageCenter {

	static ChannelService mqttChannelService;

	public static Map<String, MessageActor> actors = new ConcurrentHashMap<>();

	protected static ExecutorService executorService = Executors
			.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

	public static void sub(MessageActor actor) {
		actors.put(actor.getId(), actor);
	}

	public static void unsub(MessageActor actor) {
		actors.remove(actor.getId());
	}

	public static void onMessage(int deviceId, JSONObject message) {

		actors.values().forEach(actor -> {

			// 发送消息
			executorService.execute(() -> {

				actor.onMessage(Long.valueOf(deviceId), message);

			});

		});
	}

	public static void onLine(int i) {

		actors.values().forEach(actor -> {

			// 发送消息
			executorService.execute(() -> {

				actor.onLine(i);

			});

		});
	}

	public static void offLine(int i) {

		if (mqttChannelService == null) {

		}

		actors.values().forEach(actor -> {

			// 发送消息
			executorService.execute(() -> {

				actor.offLine(i);

			});

		});
	}

}
